<?php
/**
 * Created by PhpStorm.
 * User: 13095
 * Date: 2018/9/14
 * Time: 10:58
 */

namespace app\common\model;


use think\Db;

class Auth extends Base
{
    //自動寫入時間戳
    protected $autoWriteTimestamp = true;

    /**
     * 前置操作
     */
    protected static function init()
    {
        #添加數據結構在閉包表中
        Auth::afterInsert(function ($data) {
            $closure_data['auth_parente_id']  = $data->parent_id;
            $closure_data['auth_subclass_id'] = $data->id;
            $res                              = Db::table('pay_autn_closure')->insert($closure_data);
            if ($res) {
                return true;
            } else {
                return false;
            }
        });

        #更新數據結構在閉包表中
        Auth::afterUpdate(function ($data) {
            $closure_data['auth_parente_id'] = $data->parent_id;
            $res                             = Db::table('pay_autn_closure')->where('auth_subclass_id', '=', $data->ids)->update($closure_data);
            if ($res) {
                return true;
            } else {
                return false;
            }
        });
    }

    /**
     * 根据规则id获取规则名
     * @param $rulesId
     * @return array
     * @throws
     */
    public function useIdGetRules($rulesId, $condition = [])
    {
        empty($condition['field']) or $this->field($condition['field']);
        $res = $this->where(['id' => ['IN', $rulesId]])->select();

        $return = [];
        foreach ($res as $value) {
            $return[] = $value['auth_rules'];
        }
        return $return;
    }

    /**
     * 根据规则id获取菜单规则
     * @param $rulesId
     * @return array
     * @throws
     */
    public function useIdGetMenu($rulesId)
    {
        $res = $this->where(['id' => ['IN', $rulesId]])->select();

        $return = [];
        foreach ($res as $value) {
            if ($value['is_tyle'] == '0'){
                $return[] = [
                    'id' => $value['id'],
                    'name' => $value['auth_name'],
                    'auth_rules' => $value['auth_rules'],
                    'parent_id' => $value['parent_id']];
            }
        }
        return $return;
    }
}